package com.plan.controller.card;

import com.plan.base.constant.BaseCode;
import com.plan.base.constant.Constant;
import com.plan.base.entity.Result;
import com.plan.base.util.DateUtil;
import com.plan.controller.user.response.UserVO;
import com.plan.entity.card.DayPlan;
import com.plan.enums.DelFlagEnum;
import com.plan.service.card.PlanService;
import com.plan.service.card.TeamService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@RestController
@RequestMapping("plan/")
public class PlanController {
    @Resource
    private PlanService planService;
    @Resource
    private TeamService teamService;

    @PostMapping(value = "add")
    public Result<Long> add(@RequestBody DayPlan dayPlan, HttpServletRequest request) {
        if (dayPlan.getAwardPoint() == null || dayPlan.getName() == null
            || dayPlan.getCardId() == null || dayPlan.getTeamId() == null) {
            return Result.fail(BaseCode.PARAM_ERROR);
        }
        UserVO vo = (UserVO) request.getAttribute(Constant.USER_KEY);
        if (!teamService.isUserInTeam(dayPlan.getTeamId(), vo.getId())) {
            return Result.fail(BaseCode.ILLEGAL_OPERATION);
        }
        dayPlan.setCreatorId(vo.getId());
        dayPlan.setUpdaterId(vo.getId());
        dayPlan.setYearMonthDay(DateUtil.getYearMonthDayFromDate(new Date()));
        dayPlan.setDelFlag(DelFlagEnum.NORMAL.getType());
        return planService.insert(dayPlan);
    }
}
